package cn.momoshenchi.search.service;

import cn.momoshenchi.search.entity.SkuEsModel;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/5/6 - 19:26
 */
@Service
@Slf4j
public class ProductSaveService
{
//    @Autowired
//    private  SkuEsModelRepository skuEsModelRepository;

//    @Autowired
//    private ElasticsearchRestTemplate template;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void saveUp(List<SkuEsModel> skuEsModels) throws IOException
    {
        BulkRequest bulkRequest=new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels)
        {
            IndexRequest indexRequest=new IndexRequest("product");
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s= JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT.toBuilder().build());
        boolean failures = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if(failures)
        {
            log.error("上架错误");
        }
    }
}
